int fun(vector<int>& nums, int end, int target) {
    int left = 0, right = end;
    while (left <= right) {
        int mid = (left + right) >> 1;
        if (nums[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return left;
}
class Solution {
public:
    long long countFairPairs(vector<int>& nums, int lower, int upper) {
        ranges::sort(nums);
        long long ans = 0;
        for (int i = 0; i < nums.size(); i++) {
            int a = fun(nums, i - 1, lower - nums[i]);
            int b = fun(nums, i - 1, upper - nums[i] + 1);
            // a = min(a, i);
            // b = min(b, i);
            // cout << a << ' ' << b << endl;
            ans += b - a;
        }
        return ans;
    }
};